package com.meituan.meituanservice.service.impl;

import com.meituan.meituanservice.mapper.UserMapper;
import com.meituan.meituanservice.model.User;
import com.meituan.meituanservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public boolean register(User user) {
        User u = userMapper.selectByNick(user.getNick());
        if (u == null) {
            user.setRegisterTime(new Date());
            Integer result = userMapper.add(user);
            if (result == 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public User checkById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User login(String nick, String password) {
        return userMapper.selectByNickPassword(nick, password);
    }

    @Override
    public int updatePayCode(Integer id, String newPayCode, String oldPayCode) {
        User user = userMapper.selectById(id);
        if(user!=null){
            if(user.getPayCode()!=null){
               if(user.getPayCode().equals(oldPayCode)){
                   return userMapper.updatePayCode(id,newPayCode);
               }
            }else{
                return userMapper.updatePayCode(id,newPayCode);
            }
        }
        return 2;
    }

    @Override
    public int updateAvatar(String path, String userId) {
        return userMapper.updateAvatar(path,userId);
    }

    @Override
    public String verifyPayCode(String userId) {
        return userMapper.selectPayCodeById(userId);
    }

    @Override
    public int updatePhone(Integer id, String newPhone,String oldPhone) {
        User user = userMapper.selectById(id);
        if(user!=null){
            if(user.getPhone().equals(oldPhone)){
                return userMapper.updatePhone(id,newPhone);
            }
            return 0;
        }
        return 2;
    }

    @Override
    public User checkByNick(String nick) {
        return userMapper.selectByNick(nick);
    }
}
